<template>
  <!--文件上传icon显示列表-->
  <div style="display: flex">
    <div v-for="item in iconList" :key="item.uid" style="margin-right: 5px">
      <a
        v-if="isPreviewShow(item.name) && typeof item.name === 'string'"
        :href="item.url"
        target="_blank"
        rel="noopener noreferrer"
      >
        <img v-if="isImage(item.name)" :src="item.url" style="width: 30px; height: 30px" />
        <svg-icon v-else :name="getIconType(item.name)" :size="30" />
      </a>
      <svg-icon
        v-else-if="typeof item.name === 'string'"
        :name="getIconType(item.name)"
        :size="30"
        @click="handleDownload(item)"
      />
    </div>
  </div>
</template>

<script lang="ts">
  const fileSuffixList = [
    'doc',
    'docx',
    'xls',
    'xlsx',
    'ppt',
    'pptx',
    'pdf',
    'ogg',
    'mp3',
    'wav',
    'mp4',
    'm4v',
    'webm',
    'zip'
  ]
  const imageSuffixList = ['jpg', 'jpeg', 'png', 'gif', 'svg']
  const videoSuffixList = ['mp4', 'avi', 'flv', 'mov', 'wmv', 'mkv']
  import SvgIcon from '@/components/Icon'
  export default {
    name: 'UploadIcon',
    components: {
      SvgIcon
    },
    props: {
      iconList: {
        type: Array,
        default: () => []
      }
    },
    setup() {
      const getIconType = (fileName: string) => {
        // 文件后缀名,统一转为小写，作为icon类型使用
        const fileSuffix = fileName.split('.').pop()?.toLocaleLowerCase() ?? ''
        return fileSuffixList.includes(fileSuffix) ? fileSuffix : 'file'
      }
      // 点击预览弹窗展示的（图片和视频）
      const isPreviewShow = (fileName: string) => {
        const fileSuffix = fileName.split('.').pop()?.toLocaleLowerCase() ?? ''
        return imageSuffixList.includes(fileSuffix) || videoSuffixList.includes(fileSuffix)
      }
      // 图片类型的
      const isImage = (fileName: string) => {
        const fileSuffix = fileName.split('.').pop()?.toLocaleLowerCase() ?? ''
        return imageSuffixList.includes(fileSuffix)
      }
      const handleDownload = ({ name, url }) => {
        fetch(url)
          .then(res => res.blob())
          .then(blob => {
            const downloadElement = document.createElement('a')
            const href = window.URL.createObjectURL(blob) // 创建下载的链接
            downloadElement.href = href
            downloadElement.download = name // 下载后文件名
            downloadElement.target = '_blank'
            downloadElement.style.display = 'none'
            document.body.appendChild(downloadElement)
            downloadElement.click() // 点击下载
            document.body.removeChild(downloadElement) // 下载完成移除元素
            window.URL.revokeObjectURL(href)
          })
      }
      return {
        getIconType,
        isImage,
        handleDownload,
        isPreviewShow
      }
    }
  }
</script>
